package com.gdth.bank.activity;

import java.util.ArrayList;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.event.CjkhjlListEvent;
import com.gdth.bank.event.MessageEvent;
import com.gdth.bank.ui.CjkhZcxxFragment;
import com.gdth.bank.ui.CjkhLxfsFragment;
import com.gdth.bank.ui.CjkhBfrjFragment;
import com.gdth.bank.ui.CjkhJtcyFragment;
import com.gdth.bank.ui.CjkhQtxxFragment;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.widget.BankMenuPopupWindow;
import com.gdth.bank.widget.BankMenuPopupWindow.onPopupMenuItemClickListener;
import com.gdth.bank.widget.baiduMap.LocationBean;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.database.bean.TAppYh;
import com.gdth.service.PhoneCallService;
import com.gdth.service.PhoneCallServiceConnection;
import com.gdth.service.PhoneCallState;
import com.gdth.utils.ImageUtil;
import com.gdth.utils.PermissionUtil;
import com.gdth.widget.dialog.BaseToast;
import com.gdth.widget.viewpager.adapter.BasePagerAdapter;


/**
 * 采集客户记录详细信息页面
 * @author arvin
 *
 */

public class CjkhjlActivity extends BaseActivity{
	@ViewInject(id=R.id.header_menu) RelativeLayout txt_header;

	@ViewInject(id=R.id.header_label_title) TextView txt_header_title;
	@ViewInject(id=R.id.header_btn_left, click="finishClick") TextView txt_header_left;
    @ViewInject(id=R.id.header_btn_right, click="saveClick") TextView txt_header_right;
    @ViewInject(id=R.id.header_btn_menu, click="menuClick") TextView txt_header_menu;
    
	@ViewInject(id=R.id.visiting_view_pager) ViewPager viewPager;
	@ViewInject(id=R.id.visiting_linear_nav) LinearLayout linear_nav;
	private Drawable[] nDrawable, pDrawable;
	
	private List<TextView> textList;
 
    private Intent mServiceIntent;
 
    /**
     * 同一个应用内的不同组件间发送Broadcast
     */
    private LocalBroadcastManager mLocalBroadcastManager;
    
    /**
     * 广播载体
     */
    private MyBroadcastReceiver mMyBroadcastReceiver;
    
    private PhoneCallServiceConnection conn;
	
	/**
     * 页卡数据源
     */
    private List<View> viewList;

	private int currIndex;//当前页卡编号
	
	CjkhBfrjFragment mCjkhKhxxFragment;
	CjkhJtcyFragment mCjkhJtcyFragment;
	CjkhZcxxFragment mCjkhZcxxFragment;
	CjkhLxfsFragment mCjkhLxfsFragment;
	CjkhQtxxFragment mCjkhQtxxFragment;
	
	/** 提示框 */
    private ProgressDialog mProgressDialog;
    
    /** 唯一标识 **/
    public String jcuuid;
    public String khxm;
	public String oldzjhm = "";

    public TAppYh user;
    private boolean isSave = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cjkhjl);
		EventBus.getDefault().register(this);
		initView();
		
		init();
		
		initService();
	}

	/**
	 * 初始化页面
	 */
	@SuppressLint("NewApi")
	private void initView(){
		txt_header_menu.setVisibility(View.GONE);
		txt_header_right.setVisibility(View.GONE);
		Intent intent = this.getIntent();
		jcuuid = intent.getStringExtra("wybs");
		khxm = intent.getStringExtra("khxm");
		oldzjhm = intent.getStringExtra("zjhm");
		txt_header_title.setText(getResources().getString(R.string.param108));
		txt_header_right.setBackground(null);
		txt_header_right.setText(getResources().getString(R.string.param109));
		
		mCjkhKhxxFragment = new CjkhBfrjFragment(this);
		mCjkhKhxxFragment.setJcuuid(jcuuid);
		mCjkhKhxxFragment.setKhxm(khxm);
		mCjkhJtcyFragment = new CjkhJtcyFragment(this);
		mCjkhJtcyFragment.setJcuuid(jcuuid);
		mCjkhZcxxFragment = new CjkhZcxxFragment(this);
		mCjkhZcxxFragment.setJcuuid(jcuuid);
		mCjkhLxfsFragment = new CjkhLxfsFragment(this);
		mCjkhLxfsFragment.setJcuuid(jcuuid);
		mCjkhQtxxFragment = new CjkhQtxxFragment(this);
		mCjkhQtxxFragment.setJcuuid(jcuuid);
		//分页内容
        viewList = new ArrayList<View>();// 将要分页显示的View装入数组中 
        
        viewList.add(mCjkhKhxxFragment);
        viewList.add(mCjkhJtcyFragment);
        viewList.add(mCjkhZcxxFragment);
        viewList.add(mCjkhLxfsFragment);
        viewList.add(mCjkhQtxxFragment);
		
		//给ViewPager设置适配器
		viewPager.setAdapter(new BasePagerAdapter(viewList));
		viewPager.setCurrentItem(0);//设置当前显示标签页为第一页
		viewPager.addOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器
		
		int[] sList = new int[]{R.string.cjkh_label_khxx, R.string.cjkh_label_jtcy, R.string.cjkh_label_zcxx
				, R.string.cjkh_label_lxfs, R.string.cjkh_label_qt};
        int[] pList = new int[]{R.drawable.cjkh_cjkhxx, R.drawable.cjkh_cjjtcy, R.drawable.cjkh_cjzcxx, R.drawable.cjkh_cjlxfs, R.drawable.cjkh_cjqtxx};
        int[] nList = new int[]{R.drawable.cjkh_cjkhxx_h, R.drawable.cjkh_cjjtcy_h, R.drawable.cjkh_cjzcxx_h, R.drawable.cjkh_cjlxfs_h, R.drawable.cjkh_cjqtxx_h};
        
        nDrawable = new Drawable[sList.length];
        pDrawable = new Drawable[sList.length];
        textList = new ArrayList<TextView>();
        
    	LinearLayout.LayoutParams ll_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
        for (int i = 0; i < nList.length; i++){
        	nDrawable[i] = ImageUtil.getImageAsDrawable(this, nList[i]);
        	pDrawable[i] = ImageUtil.getImageAsDrawable(this, pList[i]);
        	TextView mTextView = new TextView(this);
        	mTextView.setText(sList[i]);
        	mTextView.setOnClickListener(new MyOnClickListener(i));
        	mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
        	
        	mTextView.setLayoutParams(ll_params);
        	
        	if (i == 0){
        		mTextView.setTextColor(AppUtil.getColor(this, R.color.cjkh_viewpager_label_light));
            	mTextView.setCompoundDrawablesWithIntrinsicBounds(null, nDrawable[i], null, null);
        	} else {
        		mTextView.setTextColor(AppUtil.getColor(this, R.color.cjkh_viewpager_label));
            	mTextView.setCompoundDrawablesWithIntrinsicBounds(null, pDrawable[i], null, null);
        	}
        	linear_nav.addView(mTextView);
        	textList.add(mTextView);
        	if(i ==0){
//        		txt_header_right.setVisibility(View.GONE);
//    			txt_header_menu.setVisibility(View.VISIBLE);
        	}
        	viewPager.setCurrentItem(currIndex);
        }
        
        mProgressDialog = new ProgressDialog(this);
        
        mPopupMenu = new BankMenuPopupWindow(this, 340, LayoutParams.WRAP_CONTENT);
        mPopupMenu.setOnPopupMenuItemClickListener(new MyOnPopupMenuItemClickListener());  
	}
	
	private void init(){
		user = BankApplication.mInstance.getCurrentUser();
		
		PermissionUtil.checkPermissionAudio(this);
		PermissionUtil.checkPermissionPhone(this);
	}
	
	/**
	 * 初始化服务
	 */
	public void initService(){
		conn = new PhoneCallServiceConnection();
		mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
		 
        mServiceIntent = new Intent(this, PhoneCallService.class);
 
//      注册各种事件
        IntentFilter mIntentFilter = getIntentFilter();
        
//      注册
        mMyBroadcastReceiver = new MyBroadcastReceiver();
        mLocalBroadcastManager.registerReceiver(mMyBroadcastReceiver, mIntentFilter);  

		bindService(mServiceIntent, conn, BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onDestroy(){
		if(conn != null)	
			unbindService(conn);
		if(mLocalBroadcastManager != null && mMyBroadcastReceiver != null)	
			mLocalBroadcastManager.unregisterReceiver(mMyBroadcastReceiver);
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
	
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void Notification(MessageEvent messageEvent) {		//
		switch (messageEvent.getType()){
			case MessageEvent.SHOWMESSAGETOAST:			
				try {
					Toast.makeText(CjkhjlActivity.this, messageEvent.getMessage(), Toast.LENGTH_SHORT).show();
				} catch (IllegalStateException e) {

				} catch (Exception e) {

				}

				break;
			
		}
	}
	
	
	@Override  
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == AppUtil.activity_map_requestcode && resultCode == AppUtil.activity_map_resultcode){
			LocationBean bean = new LocationBean();
			double jd = data.getDoubleExtra("jd", 0);
			double wd = data.getDoubleExtra("wd", 0);
			String address = data.getStringExtra("address");
			bean.setAddress(address);
			bean.setJd(jd);
			bean.setWd(wd);
			
			this.mCjkhKhxxFragment.setAddress(bean);
		}
		
		if (requestCode == AppUtil.activity_txl_requestcode && resultCode == AppUtil.activity_txl_resultcode) {
			String number = data.getStringExtra("number");
			this.mCjkhLxfsFragment.setPhoneNumber(number);
		}
		
		if (requestCode == AppUtil.activity_photo_requestcode && resultCode != 0) {
			this.mCjkhQtxxFragment.saveImage();
		}
		
		if (requestCode == AppUtil.activity_picture_requestcode && resultCode == AppUtil.activity_picture_resultcode) {
			this.mCjkhQtxxFragment.updateGridView();
		}
	}
	private long lastTime = 0;
	public void saveClick(View arg0) {
		save();
	}

	public void changejtcy(){
		mCjkhZcxxFragment.setchangejtcy();
	}
	
	public void menuClick(View arg0) {
//		int height = txt_header_menu.getHeight() ;//+ CommonTools.getStatusBarHeight(CjkhjlActivity.this);
//		int width = txt_header_menu.getWidth();
		mPopupMenu.showAsDropDown(txt_header_menu);//把Menu设置在top_layout高度开始处，右边开始处
	}
	
	private void save(){
		if(System.currentTimeMillis() - lastTime  < 1000) {
			return ;
		}
		lastTime = System.currentTimeMillis();
		EventBus.getDefault().post(new CjkhjlListEvent(CjkhjlListEvent.refreshList));
		if (currIndex == 0) {
			mCjkhKhxxFragment.save();
		} else if (currIndex == 1) {
			mCjkhJtcyFragment.save();
			mCjkhLxfsFragment.updateJtcy();
		} else if (currIndex == 2) {
			mCjkhZcxxFragment.save();
		} else if (currIndex == 3) {
			mCjkhLxfsFragment.save();
		} else if (currIndex == 4) {
			mCjkhQtxxFragment.save();
		}
	}
	
	private void edit() {
		if (currIndex == 2) {
			mCjkhZcxxFragment.edit();
		}
		if(currIndex == 0){
			mCjkhKhxxFragment.edit();
		}
	}
	
//	private void reset() {
//		if (currIndex == 2) {
//			mCjkhZcxxFragment.reset();
//		}else if(currIndex == 0){
//			mCjkhKhxxFragment.reset();
//		}
//	}
	
	private void xinZeng(){
		if(currIndex == 0){
			mCjkhKhxxFragment.reset();
		}else if(currIndex == 2){
			mCjkhZcxxFragment.reset();
		}
	}
	public void updateJtcyForLxfs() {
		mCjkhLxfsFragment.updateJtcy();
	}
	
	/**
	 * 打电话事件
	 * @param number
	 */
	public void telePhone(String jtuuid, String number){
		Intent intent = new Intent(PhoneCallState.START);
		intent.putExtra("number", number);
		intent.putExtra("jcuuid", jcuuid);
		intent.putExtra("jtuuid", jtuuid);
    	mLocalBroadcastManager.sendBroadcast(intent);
	}
	
	/**
	 * 播放音频
	 * @param uuid
	 */
	public void startMusic(String uuid){
		Intent intent = new Intent(PhoneCallState.MEDIA_STAER);
		intent.putExtra("uuid", uuid);
    	mLocalBroadcastManager.sendBroadcast(intent);
	}
	
	public void stopMusic(){
		Intent intent = new Intent(PhoneCallState.MEDIA_END);
    	mLocalBroadcastManager.sendBroadcast(intent);
	}
	
	/****************** viewpager事件 *****************/
	private class MyOnClickListener implements OnClickListener{
    	private int index=0;
    	
    	public MyOnClickListener(int i){
    		index=i;
    	}
    	
    	public void onClick(View v) {
    		viewPager.setCurrentItem(index); 
    		
        }
    }

    public class MyOnPageChangeListener implements OnPageChangeListener{
        public void onPageScrollStateChanged(int arg0) {
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        	
        }

        public void onPageSelected(int arg0) {
        	PageChange(arg0);
        }
    }
    
	private void PageChange(int arg0){
		if (arg0 == currIndex) return;
		
		changeStype(textList.get(currIndex), pDrawable[currIndex], R.color.cjkh_viewpager_label);
    	
		changeStype(textList.get(arg0), nDrawable[arg0], R.color.cjkh_viewpager_label_light);
    	
    	currIndex = arg0;
    	
//    	if (arg0 == 2) {
//			txt_header_right.setVisibility(View.GONE);
//			txt_header_menu.setVisibility(View.VISIBLE);
//    	}else  if(arg0 == 0){
//    		txt_header_right.setVisibility(View.GONE);
//			txt_header_menu.setVisibility(View.VISIBLE);
//    	}else {
//    		txt_header_right.setVisibility(View.VISIBLE);
//			txt_header_menu.setVisibility(View.GONE);
//    	}
    }
	
	/**
	 * 改变导航样式
	 * @param txt
	 * @param drawable
	 * @param color
	 */
	private void changeStype(TextView txt, Drawable drawable, int color){
		txt.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
		txt.setTextColor(AppUtil.getColor(this, color));
	}

	/****************** presener事件 *****************/
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		mProgressDialog.setMessage(msg);
		mProgressDialog.show();
	}

	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		mProgressDialog.hide();
	}

	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		BaseToast.getInstance().ShowSystemToast(this, msg);
	}
	
	/****************** 电话服务广播事件 *****************/
	@TargetApi(23)
	class MyBroadcastReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO 接收广播
			
			String action = intent.getAction();
		  
	        if (action.equals(PhoneCallState.READY)) {
	        	
	        	Intent it = new Intent();
	            //调用checkSelfPermission检查是否有权限
	         if (Build.VERSION.SDK_INT >= 23) {
	        	 if(ContextCompat.checkSelfPermission(context,  Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
	        		 String number = intent.getStringExtra("number");
		        	Intent intentPhone = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));  
		    		startActivity(intentPhone);
	        	 }else {
	        		 try {
	        			 Toast.makeText(CjkhjlActivity.this, getResources().getString(R.string.param110), Toast.LENGTH_SHORT).show();
	        			 ActivityCompat.requestPermissions( CjkhjlActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
	        			 
	        		 } catch (IllegalStateException e) {

	        		 } catch (Exception e) {
	        	 }
	        	 }
	        	 
	         } else{
	                //拥有 CALL_PHONE 权限
	            	String number = intent.getStringExtra("number");
		        	Intent intentPhone = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));  
		    		startActivity(intentPhone);
	            }

	        } 
	        
	    	if (action.equals(PhoneCallState.END)) {    
	    		String number = intent.getStringExtra("number");
	    		String jcuuid = intent.getStringExtra("jcuuid");
	    		String jtuuid = intent.getStringExtra("jtuuid");
	    		String uuid = intent.getStringExtra("uuid");
				
				mCjkhLxfsFragment.savePhoneCall(number, jcuuid, jtuuid, uuid);
	        }  
		}
		
	}
	
	/**
	 * 注册各种广播
	 * @return
	 */
	private IntentFilter getIntentFilter(){
		IntentFilter mIntentFilter = new IntentFilter();    
        mIntentFilter.addAction(PhoneCallState.IDLE);    
        mIntentFilter.addAction(PhoneCallState.DIALING);    
        mIntentFilter.addAction(PhoneCallState.ALERTING);    
        mIntentFilter.addAction(PhoneCallState.ACTIVE);    
        mIntentFilter.addAction(PhoneCallState.DISCONNECTED);
        mIntentFilter.addAction(PhoneCallState.READY);
        mIntentFilter.addAction(PhoneCallState.START);
        mIntentFilter.addAction(PhoneCallState.END);
        mIntentFilter.addAction(PhoneCallState.MEDIA_STAER);
        mIntentFilter.addAction(PhoneCallState.MEDIA_END);
            
        mIntentFilter.addAction("android.intent.action.PHONE_STATE");    
        mIntentFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        
        return mIntentFilter;
	}
	
	private BankMenuPopupWindow mPopupMenu = null;
	 
	private class MyOnPopupMenuItemClickListener implements onPopupMenuItemClickListener{

		@Override
		public void onAddButtunClick() {
			// TODO Auto-generated method stub
			save(); //保存
		}

		@Override
		public void onEditButtunClick() {
			// TODO Auto-generated method stub
			xinZeng();  //新增
		}

		@Override
		public void onDeleteButtunClick() {
			// TODO Auto-generated method stub
			edit(); //修改
//			reset();
		}		
	 }
	
	
}
